package com.deanlib.cabinet.ui.view;

import android.text.TextUtils;

import com.deanlib.cabinet.R;
import com.deanlib.cabinet.base.BaseActivity;
import com.deanlib.cabinet.data.event.UserStateEvent;
import com.deanlib.cabinet.data.network.NetWorkManager;
import com.deanlib.cabinet.databinding.ActivityLoginBinding;
import com.deanlib.cabinet.ui.Navigation;
import com.deanlib.plantern.utils.MD5Utils;
import com.deanlib.plantern.utils.PopupUtils;
import com.deanlib.cabinet.utils.UserManager;

import org.greenrobot.eventbus.EventBus;

/**
 * 登录
 * Created by Dean on 2022/6/13
 */
public class LoginActivity extends BaseActivity<ActivityLoginBinding> {
    @Override
    public void initView() {
        binding.btnLogin.setOnClickListener(view->{
            String username = binding.etUsername.getText().toString().trim();
            if (TextUtils.isEmpty(username)){
                PopupUtils.sendToast(R.string.username_cannot_be_empty);
                return;
            }
            String password = binding.etPassword.getText().toString();
            if (TextUtils.isEmpty(password)){
                PopupUtils.sendToast(R.string.password_cannot_be_empty);
                return;
            }
            request(NetWorkManager.getRequest().doLogin(username, MD5Utils.md5(password)), data->{
                UserManager.getInstance().save(data.orElse(null));
                if (UserManager.getInstance().isLogin()){
                    setResult(RESULT_OK);
                    EventBus.getDefault().postSticky(new UserStateEvent());
                    finish();
                }
            });

        });

        binding.tvRegister.setOnClickListener(view->{
            Navigation.toRegister(this);
        });
    }

    @Override
    public void loadData() {

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (UserManager.getInstance().isLogin()){
            Navigation.toMain(this);
            finish();
        }
    }
}
